package com.chen.authserver.v1.service;

import com.chen.authserver.exception.TokenParseFailureException;
import com.chen.authserver.utils.JwtUtils;
import com.chen.authserver.v1.DO.FinalAuthUser;
import com.chen.authserver.v1.repository.TokenRedisRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Map;

@Service
public class TokenService {

    @Autowired
    JwtUtils jwtUtils;

    @Autowired
    private TokenRedisRepository tokenRedisRepository;

    public String generateToken(final FinalAuthUser finalAuthUser) {
        String token = jwtUtils.createToken(String.valueOf(finalAuthUser.getId()), finalAuthUser.getAccountName(), finalAuthUser.getPwd());
        tokenRedisRepository.save(finalAuthUser.getAccountName(), token);
        return token;
    }

    /**
     * token 的合法性校验
     *
     * */
    public boolean tokenValidation(String token) {
        try {
            Map<String, Object> userInfo =  jwtUtils.parseJWT(token);
            String account = (String) userInfo.get("userAccount");
            String tokenTemp = tokenRedisRepository.get(account);
            return tokenTemp != null && tokenTemp.equals(token);
        } catch (TokenParseFailureException e) {
            return false;
        }
    }

    public boolean tokenValidation(String token, String account) {
        try {
            Map<String, Object> userInfo =  jwtUtils.parseJWT(token);
            String account1 = (String) userInfo.get("userAccount");
            String tokenTemp = tokenRedisRepository.get(account);
            return (tokenTemp != null && tokenTemp.equals(token)) && (account.equals(account1));
        } catch (TokenParseFailureException e) {
            return false;
        }
    }
}
